#include "ControlWidget.h"
#include "ui_ControlWidget.h"

ControlWidget::ControlWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ControlWidget)
{
    ui->setupUi(this);
    initUIWidget();
    initChildWidgets();


}

ControlWidget::~ControlWidget()
{
    delete ui;
}

void ControlWidget::on_treeWidget_itemActivated(QTreeWidgetItem *item, int column)
{
    this->setWindowTitle(item->text(column));
}

void ControlWidget::initUIWidget()
{

    _stack = new QStackedWidget;
    _layout = new QHBoxLayout;
    _layout->addWidget(ui->treeWidget);
    _layout->addWidget(_stack);
    _layout->setStretchFactor(ui->treeWidget,0);
    _layout->setStretchFactor(_stack,1);

    buttonBox = new QDialogButtonBox(QDialogButtonBox::Save
                                   | QDialogButtonBox::Cancel);

    connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

    _UIlayout = new QVBoxLayout(this);
    _UIlayout->addLayout(_layout);
    _layout->setStretchFactor(_layout,1);
    _UIlayout->addWidget(buttonBox);

}

void ControlWidget::initChildWidgets()
{
    _robotUI    = new RobotUI;
    _camraUI    = new CameraUI;
    _laserUI    = new LaserUI;
    _weldUI     = new WeldUI;
    _machineUI  = new MachineUI;
    _lightUI    = new LightUI;


    _stack->addWidget(_robotUI);
    _stack->addWidget(_camraUI);
    _stack->addWidget(_laserUI);
    _stack->addWidget(_weldUI);
    _stack->addWidget(_machineUI);
    _stack->addWidget(_lightUI);


    filePos     = new FilePos;
    _stack->addWidget(filePos);
    _handMoveUI     = new HandMoveUI;
    _stack->addWidget(_handMoveUI);



    _fixtureUI     = new FixtureUI;
    _stack->addWidget(_fixtureUI);

    _observedUI     = new ObservedUI;
    _stack->addWidget(_observedUI);

    _lineChart      =  new LineChart;
    _stack->addWidget(_lineChart);

    _horBarChart = new HorBarChart;
    _stack->addWidget(_horBarChart);
}

void ControlWidget::on_treeWidget_activated(const QModelIndex &index)
{
    int stackIndex = 0;
    int curIndex = index.row();
    int pa_Row = index.parent().row();

    int topLevel = ui->treeWidget->topLevelItemCount();
    for(int i =1 ;i<=topLevel;i++){
        if(i-1 < pa_Row)
            stackIndex += ui->treeWidget->topLevelItem(i-1)->childCount();
    }

    if(0 == pa_Row){
        buttonBox->setVisible(true);
        _stack->setCurrentIndex(curIndex);
    }else if(-1 == pa_Row){

    }else {
        buttonBox->setVisible(false);
        _stack->setCurrentIndex(curIndex+stackIndex);
    }
}
